import { DynamicModule, Module, Provider } from '@nestjs/common';
import { NacosNamingClientService } from './nacosNamingClient.service';
import { NacosConfigClientService } from './nacosConfigClient.service';
import { ClientOptions, NacosConfigClient, NacosNamingClient, NacosNamingClientConfig } from 'nacos';

@Module({
  providers: [NacosConfigClientService, NacosNamingClientService],
  exports: [NacosConfigClientService, NacosNamingClientService],
})
export class NacosModule {
  static forRoot(options: {
    clientOptions: ClientOptions,
    nacosNamingClientConfig: NacosNamingClientConfig,
  }): DynamicModule {
    const providers: Provider<any>[] = [
      {
        provide: 'NacosOptions',
        useValue: options,
      },
      {
        provide: 'NacosConfigClient',
        useFactory: (options: { clientOptions: ClientOptions }) => {
          return new NacosConfigClient(options.clientOptions);
        },
        inject: ['NacosOptions'],
      },
      {
        provide: 'NacosNamingClient',
        useFactory: (options: { nacosNamingClientConfig: NacosNamingClientConfig }) => {
          return new NacosNamingClient(options.nacosNamingClientConfig);
        },
        inject: ['NacosOptions'],
      },
      NacosConfigClientService,
      NacosNamingClientService,
    ];

    return {
      module: NacosModule,
      providers,
      exports: [
        'NacosConfigClient',
        'NacosNamingClient',
        NacosConfigClientService,
        NacosNamingClientService,
      ],
    };
  }
}
